package map.core.util;

import org.geotools.api.filter.FilterFactory;
import org.geotools.api.filter.sort.SortBy;
import org.geotools.api.filter.sort.SortOrder;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.util.factory.GeoTools;
import org.locationtech.jts.geom.*;

public class GeoHelper {
    public static CoordinateReferenceSystem WGS84 = DefaultGeographicCRS.WGS84;
    public static CoordinateReferenceSystem WEB_MERCATOR;

    public static GeometryFactory gfc = new GeometryFactory();


    public static MathTransform WGS84_TO_WEB_MERCATOR;



    static {
        try {
            WEB_MERCATOR = CRS.decode("EPSG:3857", true);
            WGS84_TO_WEB_MERCATOR = CRS.findMathTransform(WGS84,WEB_MERCATOR,true);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static SortBy[] createSortBy(String orderByFields) {
        FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());

        String[] strSortBies = orderByFields.split(",");
        SortBy[] sortBies = new SortBy[strSortBies.length];
        for (int i = 0; i < strSortBies.length; i++) {
            String strSortBy = strSortBies[i];
            String[] strs = strSortBy.trim().split(" ");

            SortOrder order = SortOrder.ASCENDING;

            if (strs.length == 2) {
                String strOrder = strs[1].toUpperCase().trim();
                if ("DESC".equals(strOrder)) {
                    order = SortOrder.DESCENDING;
                }
            }
            sortBies[i] = ff.sort(strs[0], order);
        }
        return sortBies;
    }

    public static Polygon toPolygon(Envelope env) {
        final Coordinate[] coords = new Coordinate[5];
        coords[0] = new Coordinate( env.getMinX(), env.getMinY() );
        coords[1] = new Coordinate( env.getMinX(), env.getMaxY() );
        coords[2] = new Coordinate( env.getMaxX(), env.getMaxY() );
        coords[3] = new Coordinate( env.getMaxX(), env.getMinY() );
        coords[4] = new Coordinate( env.getMinX(), env.getMinY() );
        final LinearRing shell = gfc.createLinearRing( coords );
        return gfc.createPolygon( shell, null );


    }
}
